<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.2/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"littlefxc.github.io","root":"/","images":"/images","scheme":"Mist","version":"8.2.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}};
  </script>
<meta name="description" content="转载自https:&#x2F;&#x2F;mp.weixin.qq.com&#x2F;s&#x2F;8aMz07rOF5LuclnBaI_p5g   今天又要给大家介绍一个 Spring Boot 中的组件–HandlerMethodReturnValueHandler。 在前面的文章中（如何优雅的实现 Spring Boot 接口参数加密解密？），松哥已经和大家介绍过如何对请求&#x2F;响应数据进行预处理&#x2F;二次处理，当时我们使用了 Resp">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring Boot 中如何统一 API 接口响应格式？">
<meta property="og:url" content="http://littlefxc.github.io/2021/03/22/Spring-Boot-%E4%B8%AD%E5%A6%82%E4%BD%95%E7%BB%9F%E4%B8%80-API-%E6%8E%A5%E5%8F%A3%E5%93%8D%E5%BA%94%E6%A0%BC%E5%BC%8F%EF%BC%9F/index.html">
<meta property="og:site_name" content="一年春又来">
<meta property="og:description" content="转载自https:&#x2F;&#x2F;mp.weixin.qq.com&#x2F;s&#x2F;8aMz07rOF5LuclnBaI_p5g   今天又要给大家介绍一个 Spring Boot 中的组件–HandlerMethodReturnValueHandler。 在前面的文章中（如何优雅的实现 Spring Boot 接口参数加密解密？），松哥已经和大家介绍过如何对请求&#x2F;响应数据进行预处理&#x2F;二次处理，当时我们使用了 Resp">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/640.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/640-20210322193325348.png">
<meta property="article:published_time" content="2021-03-22T11:30:14.000Z">
<meta property="article:modified_time" content="2021-03-25T13:59:09.470Z">
<meta property="article:author" content="一年春又来">
<meta property="article:tag" content="spring boot">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/littlefxc/oss/raw/master/images/640.png">


<link rel="canonical" href="http://littlefxc.github.io/2021/03/22/Spring-Boot-%E4%B8%AD%E5%A6%82%E4%BD%95%E7%BB%9F%E4%B8%80-API-%E6%8E%A5%E5%8F%A3%E5%93%8D%E5%BA%94%E6%A0%BC%E5%BC%8F%EF%BC%9F/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>
<title>Spring Boot 中如何统一 API 接口响应格式？ | 一年春又来</title>
  




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="一年春又来" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">一年春又来</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="home                          //首页 fa-fw"></i>首页</a></li>
        <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="archive          //归档 fa-fw"></i>归档</a></li>
        <li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="th           //分类 fa-fw"></i>分类</a></li>
        <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="tags                     //标签 fa-fw"></i>标签</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-HandlerMethodReturnValueHandler"><span class="nav-text">1.HandlerMethodReturnValueHandler</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-ModelAndViewContainer"><span class="nav-text">2.ModelAndViewContainer</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-API-%E6%8E%A5%E5%8F%A3%E6%95%B0%E6%8D%AE%E5%8C%85%E8%A3%85"><span class="nav-text">3.API 接口数据包装</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-RequestResponseBodyMethodProcessor"><span class="nav-text">3.1 RequestResponseBodyMethodProcessor</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2-%E5%85%B7%E4%BD%93%E5%AE%9E%E7%8E%B0"><span class="nav-text">3.2 具体实现</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-%E5%B0%8F%E7%BB%93"><span class="nav-text">4.小结</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">一年春又来</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">234</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">38</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">125</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://littlefxc.github.io/2021/03/22/Spring-Boot-%E4%B8%AD%E5%A6%82%E4%BD%95%E7%BB%9F%E4%B8%80-API-%E6%8E%A5%E5%8F%A3%E5%93%8D%E5%BA%94%E6%A0%BC%E5%BC%8F%EF%BC%9F/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="一年春又来">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一年春又来">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Spring Boot 中如何统一 API 接口响应格式？
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2021-03-22 19:30:14" itemprop="dateCreated datePublished" datetime="2021-03-22T19:30:14+08:00">2021-03-22</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2021-03-25 21:59:09" itemprop="dateModified" datetime="2021-03-25T21:59:09+08:00">2021-03-25</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/spring/" itemprop="url" rel="index"><span itemprop="name">spring</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <blockquote>
<p>转载自<a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/8aMz07rOF5LuclnBaI_p5g">https://mp.weixin.qq.com/s/8aMz07rOF5LuclnBaI_p5g</a></p>
</blockquote>
<hr>
<p>今天又要给大家介绍一个 Spring Boot 中的组件–HandlerMethodReturnValueHandler。</p>
<p>在前面的文章中（<a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s?__biz=MzI1NDY0MTkzNQ==&mid=2247492446&idx=1&sn=d75472fed90752c609a918aefd2796d4&scene=21#wechat_redirect">如何优雅的实现 Spring Boot 接口参数加密解密？</a>），松哥已经和大家介绍过如何对请求/响应数据进行预处理/二次处理，当时我们使用了 ResponseBodyAdvice 和 RequestBodyAdvice。其中 ResponseBodyAdvice 可以实现对响应数据的二次处理，可以在这里对响应数据进行加密/包装等等操作。不过这不是唯一的方案，今天松哥要和大家介绍一种更加灵活的方案–HandlerMethodReturnValueHandler，我们一起来看看下。</p>
<span id="more"></span>

<h2 id="1-HandlerMethodReturnValueHandler"><a href="#1-HandlerMethodReturnValueHandler" class="headerlink" title="1.HandlerMethodReturnValueHandler"></a><strong>1.HandlerMethodReturnValueHandler</strong></h2><p>HandlerMethodReturnValueHandler 的作用是对处理器的处理结果再进行一次二次加工，这个接口里边有两个方法：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">public interface HandlerMethodReturnValueHandler &#123;</span><br><span class="line"> boolean supportsReturnType(MethodParameter returnType);</span><br><span class="line"> void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType,</span><br><span class="line">   ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>supportsReturnType：这个处理器是否支持相应的返回值类型。</li>
<li>handleReturnValue：对方法返回值进行处理。</li>
</ul>
<p>HandlerMethodReturnValueHandler 有很多默认的实现类，我们来看下：</p>
<p><img src="https://gitee.com/littlefxc/oss/raw/master/images/640.png" alt="img"></p>
<p>接下来我们来把这些实现类的作用捋一捋：</p>
<p><strong>ViewNameMethodReturnValueHandler</strong></p>
<p>这个处理器用来处理返回值为 void 和 String 的情况。如果返回值为 void，则不做任何处理。如果返回值为 String，则将 String 设置给 mavContainer 的 viewName 属性，同时判断这个 String 是不是重定向的 String，如果是，则设置 mavContainer 的 redirectModelScenario 属性为 true，这是处理器返回重定向视图的标志。</p>
<p><strong>ViewMethodReturnValueHandler</strong></p>
<p>这个处理器用来处理返回值为 View 的情况。如果返回值为 View，则将 View 设置给 mavContainer 的 view 属性，同时判断这个 View 是不是重定向的 View，如果是，则设置 mavContainer 的 redirectModelScenario 属性为 true，这是处理器返回重定向视图的标志。</p>
<p><strong>MapMethodProcessor</strong></p>
<p>这个处理器用来处理返回值类型为 Map 的情况，具体的处理方案就是将 map 添加到 mavContainer 的 model 属性中。</p>
<p><strong>StreamingResponseBodyReturnValueHandler</strong></p>
<p>这个用来处理 StreamingResponseBody 或者 <code>ResponseEntity&lt;StreamingResponseBody&gt;</code> 类型的返回值。</p>
<p><strong>DeferredResultMethodReturnValueHandler</strong></p>
<p>这个用来处理 DeferredResult、ListenableFuture 以及 CompletionStage 类型的返回值，用于异步请求。</p>
<p><strong>CallableMethodReturnValueHandler</strong></p>
<p>处理 Callable 类型的返回值，也是用于异步请求。</p>
<p><strong>HttpHeadersReturnValueHandler</strong></p>
<p>这个用来处理 HttpHeaders 类型的返回值，具体处理方式就是将 mavContainer 中的 requestHandled 属性设置为 true，该属性是请求是否已经处理完成的标志（如果处理完了，就到此为止，后面不会再去找视图了），然后将 HttpHeaders 添加到响应头中。</p>
<p><strong>ModelMethodProcessor</strong></p>
<p>这个用来处理返回值类型为 Model 的情况，具体的处理方式就是将 Model 添加到 mavContainer 的 model 上。</p>
<p><strong>ModelAttributeMethodProcessor</strong></p>
<p>这个用来处理添加了 <code>@ModelAttribute</code> 注解的返回值类型，如果 annotaionNotRequired 属性为 true，也可以用来处理其他非通用类型的返回值。</p>
<p><strong>ServletModelAttributeMethodProcessor</strong></p>
<p>同上，该类只是修改了参数解析方式。</p>
<p><strong>ResponseBodyEmitterReturnValueHandler</strong></p>
<p>这个用来处理返回值类型为 <code>ResponseBodyEmitter</code> 的情况。</p>
<p><strong>ModelAndViewMethodReturnValueHandler</strong></p>
<p>这个用来处理返回值类型为 <code>ModelAndView</code> 的情况，将返回值中的 Model 和 View 分别设置到 mavContainer 的相应属性上去。</p>
<p><strong>ModelAndViewResolverMethodReturnValueHandler</strong></p>
<p>这个的 supportsReturnType 方法返回 true，即可以处理所有类型的返回值，这个一般放在最后兜底。</p>
<p><strong>AbstractMessageConverterMethodProcessor</strong></p>
<p>这是一个抽象类，当返回值需要通过 HttpMessageConverter 进行转化的时候会用到它的子类。这个抽象类主要是定义了一些工具方法。</p>
<p><strong>RequestResponseBodyMethodProcessor</strong></p>
<p>这个用来处理添加了 <code>@ResponseBody</code> 注解的返回值类型。</p>
<p><strong>HttpEntityMethodProcessor</strong></p>
<p>这个用来处理返回值类型是 HttpEntity 并且不是 RequestEntity 的情况。</p>
<p><strong>AsyncHandlerMethodReturnValueHandler</strong></p>
<p>这是一个空接口，暂未发现典型使用场景。</p>
<p><strong>AsyncTaskMethodReturnValueHandler</strong></p>
<p>这个用来处理返回值类型为 WebAsyncTask 的情况。</p>
<p><strong>HandlerMethodReturnValueHandlerComposite</strong></p>
<p>看 Composite 就知道，这是一个组合处理器，没啥好说的。</p>
<p>这个就是系统默认定义的 HandlerMethodReturnValueHandler。</p>
<p>那么在上面的介绍中，大家看到反复涉及到一个组件 mavContainer，这个我也要和大家介绍一下。</p>
<h2 id="2-ModelAndViewContainer"><a href="#2-ModelAndViewContainer" class="headerlink" title="2.ModelAndViewContainer"></a><strong>2.ModelAndViewContainer</strong></h2><p>ModelAndViewContainer 就是一个数据穿梭巴士，在整个请求的过程中承担着数据传送的工作，从它的名字上我们可以看出来它里边保存着 Model 和 View 两种类型的数据，但是实际上可不止两种，我们来看下 ModelAndViewContainer 的定义：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">public class ModelAndViewContainer &#123;</span><br><span class="line"> private boolean ignoreDefaultModelOnRedirect &#x3D; false;</span><br><span class="line"> @Nullable</span><br><span class="line"> private Object view;</span><br><span class="line"> private final ModelMap defaultModel &#x3D; new BindingAwareModelMap();</span><br><span class="line"> @Nullable</span><br><span class="line"> private ModelMap redirectModel;</span><br><span class="line"> private boolean redirectModelScenario &#x3D; false;</span><br><span class="line"> @Nullable</span><br><span class="line"> private HttpStatus status;</span><br><span class="line"> private final Set&lt;String&gt; noBinding &#x3D; new HashSet&lt;&gt;(4);</span><br><span class="line"> private final Set&lt;String&gt; bindingDisabled &#x3D; new HashSet&lt;&gt;(4);</span><br><span class="line"> private final SessionStatus sessionStatus &#x3D; new SimpleSessionStatus();</span><br><span class="line"> private boolean requestHandled &#x3D; false;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>把这几个属性理解了，基本上也就整明白 ModelAndViewContainer 的作用了：</p>
<ul>
<li>defaultModel：默认使用的 Model。当我们在接口参数重使用 Model、ModelMap 或者 Map 时，最终使用的实现类都是 BindingAwareModelMap，对应的也都是 defaultModel。</li>
<li>redirectModel：重定向时候的 Model，如果我们在接口参数中使用了 RedirectAttributes 类型的参数，那么最终会传入 redirectModel。</li>
</ul>
<p>可以看到，一共有两个 Model，两个 Model 到底用哪个呢？这个在 getModel 方法中根据条件返回合适的 Model：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">public ModelMap getModel() &#123;</span><br><span class="line"> if (useDefaultModel()) &#123;</span><br><span class="line">  return this.defaultModel;</span><br><span class="line"> &#125;</span><br><span class="line"> else &#123;</span><br><span class="line">  if (this.redirectModel &#x3D;&#x3D; null) &#123;</span><br><span class="line">   this.redirectModel &#x3D; new ModelMap();</span><br><span class="line">  &#125;</span><br><span class="line">  return this.redirectModel;</span><br><span class="line"> &#125;</span><br><span class="line">&#125;</span><br><span class="line">private boolean useDefaultModel() &#123;</span><br><span class="line"> return (!this.redirectModelScenario || (this.redirectModel &#x3D;&#x3D; null &amp;&amp; !this.ignoreDefaultModelOnRedirect));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里 redirectModelScenario 表示处理器是否返回 redirect 视图；ignoreDefaultModelOnRedirect 表示是否在重定向时忽略 defaultModel，所以这块的逻辑是这样：</p>
<ol>
<li>如果 redirectModelScenario 为 true，即处理器返回的是一个重定向视图，那么使用 redirectModel。如果 redirectModelScenario 为 false，即处理器返回的不是一个重定向视图，那么使用 defaultModel。</li>
<li>如果 redirectModel 为 null，并且 ignoreDefaultModelOnRedirect 为 false，则使用 redirectModel，否则使用 defaultModel。</li>
</ol>
<p>接下来还剩下如下一些参数：</p>
<ul>
<li>view：返回的视图。</li>
<li>status：HTTP 状态码。</li>
<li>noBinding：是否对 @ModelAttribute(binding=true/false) 声明的数据模型的相应属性进行绑定。</li>
<li>bindingDisabled：不需要进行数据绑定的属性。</li>
<li>sessionStatus：SessionAttribute 使用完成的标识。</li>
<li>requestHandled：请求处理完成的标识（例如添加了 <code>@ResponseBody</code> 注解的接口，这个属性为 true，请求就不会再去找视图了）。</li>
</ul>
<blockquote>
<p>❝这个 ModelAndViewContainer 小伙伴们权且做一个了解，松哥在后面的源码分析中，还会和大家再次聊到这个组件。</p>
</blockquote>
<p>接下来我们也来自定义一个 HandlerMethodReturnValueHandler，来感受一下 HandlerMethodReturnValueHandler 的基本用法。</p>
<h2 id="3-API-接口数据包装"><a href="#3-API-接口数据包装" class="headerlink" title="3.API 接口数据包装"></a><strong>3.API 接口数据包装</strong></h2><p>假设我有这样一个需求：我想在原始的返回数据外面再包裹一层，举个简单例子，本来接口是下面这样：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">@RestController</span><br><span class="line">public class UserController &#123;</span><br><span class="line">    @GetMapping(&quot;&#x2F;user&quot;)</span><br><span class="line">    public User getUserByUsername(String username) &#123;</span><br><span class="line">        User user &#x3D; new User();</span><br><span class="line">        user.setUsername(username);</span><br><span class="line">        user.setAddress(&quot;www.javaboy.org&quot;);</span><br><span class="line">        return user;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>返回的数据格式是下面这样：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#123;&quot;username&quot;:&quot;javaboy&quot;,&quot;address&quot;:&quot;www.javaboy.org&quot;&#125;</span><br></pre></td></tr></table></figure>

<p>现在我希望返回的数据格式变成下面这样：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#123;&quot;status&quot;:&quot;ok&quot;,&quot;data&quot;:&#123;&quot;username&quot;:&quot;javaboy&quot;,&quot;address&quot;:&quot;www.javaboy.org&quot;&#125;&#125;</span><br></pre></td></tr></table></figure>

<p>就这样一个简单需求，我们一起来看下怎么实现。</p>
<h3 id="3-1-RequestResponseBodyMethodProcessor"><a href="#3-1-RequestResponseBodyMethodProcessor" class="headerlink" title="3.1 RequestResponseBodyMethodProcessor"></a><strong>3.1 RequestResponseBodyMethodProcessor</strong></h3><p>在开始定义之前，先给大家介绍一下 RequestResponseBodyMethodProcessor，这是 HandlerMethodReturnValueHandler 的实现类之一，这个主要用来处理返回 JSON 的情况。</p>
<p>我们来稍微看下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">@Override</span><br><span class="line">public boolean supportsReturnType(MethodParameter returnType) &#123;</span><br><span class="line"> return (AnnotatedElementUtils.hasAnnotation(returnType.getContainingClass(), ResponseBody.class) ||</span><br><span class="line">   returnType.hasMethodAnnotation(ResponseBody.class));</span><br><span class="line">&#125;</span><br><span class="line">@Override</span><br><span class="line">public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType,</span><br><span class="line">  ModelAndViewContainer mavContainer, NativeWebRequest webRequest)</span><br><span class="line">  throws IOException, HttpMediaTypeNotAcceptableException, HttpMessageNotWritableException &#123;</span><br><span class="line"> mavContainer.setRequestHandled(true);</span><br><span class="line"> ServletServerHttpRequest inputMessage &#x3D; createInputMessage(webRequest);</span><br><span class="line"> ServletServerHttpResponse outputMessage &#x3D; createOutputMessage(webRequest);</span><br><span class="line"> writeWithMessageConverters(returnValue, returnType, inputMessage, outputMessage);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>supportsReturnType：从这个方法中可以看到，这里支持有 <code>@ResponseBody</code> 注解的接口。</li>
<li>handleReturnValue：这是具体的处理逻辑，首先 mavContainer 中设置 requestHandled 属性为 true，表示这里处理完成后就完了，以后不用再去找视图了，然后分别获取 inputMessage 和 outputMessage，调用 writeWithMessageConverters 方法进行输出，writeWithMessageConverters 方法是在父类中定义的方法，这个方法比较长，核心逻辑就是调用确定输出数据、确定 MediaType，然后通过 HttpMessageConverter 将 JSON 数据写出去即可。</li>
</ul>
<p>有了上面的知识储备之后，接下来我们就可以自己实现了。</p>
<h3 id="3-2-具体实现"><a href="#3-2-具体实现" class="headerlink" title="3.2 具体实现"></a><strong>3.2 具体实现</strong></h3><p>首先自定义一个 HandlerMethodReturnValueHandler：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyHandlerMethodReturnValueHandler</span> <span class="keyword">implements</span> <span class="title">HandlerMethodReturnValueHandler</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> HandlerMethodReturnValueHandler handler;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">MyHandlerMethodReturnValueHandler</span><span class="params">(HandlerMethodReturnValueHandler handler)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.handler = handler;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">supportsReturnType</span><span class="params">(MethodParameter returnType)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> handler.supportsReturnType(returnType);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">handleReturnValue</span><span class="params">(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        Map&lt;String, Object&gt; map = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line">        map.put(<span class="string">&quot;status&quot;</span>, <span class="string">&quot;ok&quot;</span>);</span><br><span class="line">        map.put(<span class="string">&quot;data&quot;</span>, returnValue);</span><br><span class="line">        handler.handleReturnValue(map, returnType, mavContainer, webRequest);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>由于我们要做的功能其实是在 RequestResponseBodyMethodProcessor 基础之上实现的，因为支持 <code>@ResponseBody</code>，输出 JSON 那些东西都不变，我们只是在输出之前修改一下数据而已。所以我这里直接定义了一个属性 HandlerMethodReturnValueHandler，这个属性的实例就是 RequestResponseBodyMethodProcessor，supportsReturnType 方法就按照 RequestResponseBodyMethodProcessor 的要求来，在 handleReturnValue 方法中，我们先对返回值进行一个预处理，然后调用 RequestResponseBodyMethodProcessor#handleReturnValue 方法继续输出 JSON 即可。</p>
<p>接下来就是配置 MyHandlerMethodReturnValueHandler 使之生效了。由于 SpringMVC 中 HandlerAdapter 在加载的时候已经配置了 HandlerMethodReturnValueHandler（这块松哥以后会和大家分析相关源码），所以我们可以通过如下方式对已经配置好的 RequestMappingHandlerAdapter 进行修改，如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">@Configuration</span><br><span class="line">public class ReturnValueConfig implements InitializingBean &#123;</span><br><span class="line">    @Autowired</span><br><span class="line">    RequestMappingHandlerAdapter requestMappingHandlerAdapter;</span><br><span class="line">    @Override</span><br><span class="line">    public void afterPropertiesSet() throws Exception &#123;</span><br><span class="line">        List&lt;HandlerMethodReturnValueHandler&gt; originHandlers &#x3D; requestMappingHandlerAdapter.getReturnValueHandlers();</span><br><span class="line">        List&lt;HandlerMethodReturnValueHandler&gt; newHandlers &#x3D; new ArrayList&lt;&gt;(originHandlers.size());</span><br><span class="line">        for (HandlerMethodReturnValueHandler originHandler : originHandlers) &#123;</span><br><span class="line">            if (originHandler instanceof RequestResponseBodyMethodProcessor) &#123;</span><br><span class="line">                newHandlers.add(new MyHandlerMethodReturnValueHandler(originHandler));</span><br><span class="line">            &#125;else&#123;</span><br><span class="line">                newHandlers.add(originHandler);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        requestMappingHandlerAdapter.setReturnValueHandlers(newHandlers);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>自定义 ReturnValueConfig 实现 InitializingBean 接口，afterPropertiesSet 方法会被自动调用，在该方法中，我们将 RequestMappingHandlerAdapter 中已经配置好的 HandlerMethodReturnValueHandler 拎出来挨个检查，如果类型是 RequestResponseBodyMethodProcessor，则重新构建，用我们自定义的 MyHandlerMethodReturnValueHandler 代替它，最后给 requestMappingHandlerAdapter 重新设置 HandlerMethodReturnValueHandler 即可。</p>
<p>最后再提供一个测试接口：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">@RestController</span><br><span class="line">public class UserController &#123;</span><br><span class="line">    @GetMapping(&quot;&#x2F;user&quot;)</span><br><span class="line">    public User getUserByUsername(String username) &#123;</span><br><span class="line">        User user &#x3D; new User();</span><br><span class="line">        user.setUsername(username);</span><br><span class="line">        user.setAddress(&quot;www.javaboy.org&quot;);</span><br><span class="line">        return user;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">public class User &#123;</span><br><span class="line">    private String username;</span><br><span class="line">    private String address;</span><br><span class="line">&#x2F;&#x2F;省略其他</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>配置完成后，就可以启动项目啦。</p>
<p>项目启动成功后，访问 <code>/user</code> 接口，如下：</p>
<p><img src="https://gitee.com/littlefxc/oss/raw/master/images/640-20210322193325348.png" alt="img"></p>
<p>完美。</p>
<h2 id="4-小结"><a href="#4-小结" class="headerlink" title="4.小结"></a><strong>4.小结</strong></h2><p>其实统一 API 接口响应格式办法很多，可以参考松哥之前分享的 <a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s?__biz=MzI1NDY0MTkzNQ==&mid=2247492446&idx=1&sn=d75472fed90752c609a918aefd2796d4&scene=21#wechat_redirect">如何优雅的实现 Spring Boot 接口参数加密解密？</a>，也可以使用本文中的方案，甚至也可以自定义过滤器实现。</p>
<p>本文的内容稍微有点多，不知道大家有没有发现松哥最近发了很多 SpringMVC 源码相关的东西，没错，本文其实是松哥 SpringMVC 源码解析的一部分，为了源码解析不那么枯燥，所以强行加了一个案例进来，祝小伙伴们学习愉快～</p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/spring-boot/" rel="tag"># spring boot</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2021/03/22/Java%E5%A4%9A%E7%BA%BF%E7%A8%8BJUC%E9%94%81-%E7%AE%80%E4%BB%8B/" rel="prev" title="Java多线程JUC锁-简介">
                  <i class="fa fa-chevron-left"></i> Java多线程JUC锁-简介
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2021/03/24/Spring-Integration-1/" rel="next" title="Spring Integration(1)">
                  Spring Integration(1) <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>







<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">一年春又来</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/mist/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  
<script src="/js/local-search.js"></script>






  





</body>
</html>
